# == Schema Information
#
# Table name: base_users
#
#  id            :integer          not null, primary key
#  name_cn       :string(255)
#  gender        :boolean
#  username      :string(255)
#  password      :string(255)
#  active        :boolean          default(TRUE)
#  department_id :integer
#  email         :string(255)
#  mobile        :string(255)
#  last_login_at :datetime
#  leave_time    :date
#  phone_ext     :string(255)
#  customer_id   :integer
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#

class Base::User < ApplicationRecord
  extend Enumerize
  include Permission
  belongs_to :department, :class_name => 'Base::Department', foreign_key: 'department_id'
  belongs_to :customer

  scope :this, -> { where(customer_id: Customer.current&.id)}

  scope :active, -> { where(active: true) }

  GENDER = {male: 1, female: 0}
  enumerize :gender, in: GENDER,  predicates: {prefix: true}, scope: true

  validates_presence_of :mobile, message: '请填写注册手机号'
  validates_presence_of :password, message: '请输入密码'
  # validates_uniqueness_of :username, message: '用户名重复'
  # /^1[34578]\d{9}$/
  # validates_uniqueness_of :mobile

  def to_s
    self.name_cn || self.username
  end

  def password=(pwd)
    super Digest::MD5.hexdigest(pwd)
  end

  def resign!
    self.update(active: false)
  end

  def self.find(*args)
    return Base::User.new(username: 'system', name_cn: 'system') if args[0].to_i==0
    super(*args)
  end

  # 在model里面获取的当前用户
  def self.current
    Base::Session.current_user
  end

  def self.valid_users(params)
    if %w[xyy joel peter system].include?(params[:username])
      self.active.where(username: params[:username], password: Digest::MD5.hexdigest(params[:password]))
    else
      t = self.active.where(mobile: params[:username], password: Digest::MD5.hexdigest(params[:password]))
      t = t.where(customer_id: params[:customer_id]) unless params[:customer_id].blank?
      t
    end
  end
end
